import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { liveStreamAPI } from '../services/api';
import { LiveStream } from '../types';
import Avatar from '../components/Avatar';

const LiveStreamView: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [liveStream, setLiveStream] = useState<LiveStream | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [isLiked, setIsLiked] = useState(false);
  const videoRef = useRef<HTMLVideoElement>(null);
  const peerConnectionRef = useRef<RTCPeerConnection | null>(null);

  const showSimulatedStream = useCallback(() => {
    if (!videoRef.current) return;
    
    // 创建模拟视频流
    const canvas = document.createElement('canvas');
    canvas.width = 640;
    canvas.height = 480;
    const ctx = canvas.getContext('2d')!;
    
    let frameCount = 0;
    const drawFrame = () => {
      // 清空画布
      ctx.fillStyle = '#1f2937';
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      
      // 绘制模拟内容
      ctx.fillStyle = '#3b82f6';
      ctx.font = '48px Arial';
      ctx.textAlign = 'center';
      ctx.fillText('模拟直播', canvas.width / 2, canvas.height / 2 - 50);
      
      ctx.fillStyle = '#ffffff';
      ctx.font = '24px Arial';
      ctx.fillText(`观看时间: ${Math.floor(frameCount / 30)}秒`, canvas.width / 2, canvas.height / 2);
      
      ctx.fillStyle = '#10b981';
      ctx.font = '20px Arial';
      ctx.fillText('正在观看直播...', canvas.width / 2, canvas.height / 2 + 50);
      
      // 添加动画效果
      ctx.fillStyle = `hsl(${(frameCount * 3) % 360}, 70%, 60%)`;
      ctx.beginPath();
      ctx.arc(150 + Math.sin(frameCount * 0.1) * 100, 150 + Math.cos(frameCount * 0.1) * 50, 15, 0, 2 * Math.PI);
      ctx.fill();
      
      frameCount++;
      requestAnimationFrame(drawFrame);
    };
    
    drawFrame();
    
    // 将canvas转换为MediaStream并播放
    const stream = canvas.captureStream(30);
    videoRef.current.srcObject = stream;
  }, []);

  const handleOffer = useCallback(async (message: any) => {
    if (!peerConnectionRef.current) return;
    
    try {
      await peerConnectionRef.current.setRemoteDescription(new RTCSessionDescription(message.offer));
      const answer = await peerConnectionRef.current.createAnswer();
      await peerConnectionRef.current.setLocalDescription(answer);
      
      // 发送answer
      // 这里需要通过WebSocket发送
    } catch (error) {
      console.error('处理offer失败:', error);
    }
  }, []);

  const handleIceCandidate = useCallback(async (message: any) => {
    if (!peerConnectionRef.current) return;
    
    try {
      await peerConnectionRef.current.addIceCandidate(new RTCIceCandidate(message.candidate));
    } catch (error) {
      console.error('处理ICE候选失败:', error);
    }
  }, []);

  const initializeWebRTC = useCallback(async (streamKey: string) => {
    try {
      // 创建WebSocket连接
      const socket = new WebSocket('ws://localhost:8080/ws');
      
      socket.onopen = () => {
        console.log('WebSocket连接已建立');
        // 加入直播流
        socket.send(JSON.stringify({
          type: 'join',
          streamKey: streamKey,
          userId: 'viewer'
        }));
      };

      socket.onmessage = async (event) => {
        const message = JSON.parse(event.data);
        
        switch (message.type) {
          case 'offer':
            await handleOffer(message);
            break;
          case 'ice-candidate':
            await handleIceCandidate(message);
            break;
        }
      };

      socket.onerror = (error) => {
        console.error('WebSocket连接错误:', error);
        // 如果WebSocket连接失败，显示模拟直播内容
        showSimulatedStream();
      };

      socket.onclose = () => {
        console.log('WebSocket连接已关闭');
        // 连接关闭时显示模拟内容
        showSimulatedStream();
      };

      // 创建RTCPeerConnection
      const configuration = {
        iceServers: [
          { urls: 'stun:stun.l.google.com:19302' }
        ]
      };
      
      peerConnectionRef.current = new RTCPeerConnection(configuration);
      
      // 处理远程流
      peerConnectionRef.current.ontrack = (event) => {
        if (videoRef.current) {
          videoRef.current.srcObject = event.streams[0];
        }
      };

      // 处理ICE候选
      peerConnectionRef.current.onicecandidate = (event) => {
        if (event.candidate) {
          socket.send(JSON.stringify({
            type: 'ice-candidate',
            candidate: event.candidate
          }));
        }
      };

      // 如果5秒内没有收到流，显示模拟内容
      setTimeout(() => {
        if (videoRef.current && !videoRef.current.srcObject) {
          showSimulatedStream();
        }
      }, 5000);

    } catch (error) {
      console.error('WebRTC初始化失败:', error);
      showSimulatedStream();
    }
  }, [showSimulatedStream, handleOffer, handleIceCandidate]);

  const fetchLiveStream = useCallback(async () => {
    try {
      setLoading(true);
      const stream = await liveStreamAPI.getLiveStreamById(parseInt(id!));
      setLiveStream(stream);
      
      // 如果是直播中，开始WebRTC连接
      if (stream.status === 'LIVE') {
        initializeWebRTC(stream.streamKey);
      }
    } catch (error: any) {
      setError(error.message || '获取直播信息失败');
    } finally {
      setLoading(false);
    }
  }, [id, initializeWebRTC]);

  useEffect(() => {
    if (id) {
      fetchLiveStream();
    }
  }, [id, fetchLiveStream]);

  const handleLike = async () => {
    if (!liveStream) return;
    
    try {
      await liveStreamAPI.likeLiveStream(liveStream.id);
      setIsLiked(true);
      setLiveStream(prev => prev ? { ...prev, likes: prev.likes + 1 } : null);
    } catch (error: any) {
      console.error('点赞失败:', error);
    }
  };

  if (loading) {
    return (
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="text-center py-8">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">加载中...</p>
        </div>
      </div>
    );
  }

  if (error || !liveStream) {
    return (
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded">
          {error || '直播不存在'}
        </div>
        <button 
          onClick={() => navigate('/live')}
          className="mt-4 btn btn-primary"
        >
          返回直播列表
        </button>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-4 md:py-8">
      <div className="bg-white rounded-lg shadow overflow-hidden">
        {/* 视频播放区域 */}
        <div className="aspect-video bg-gray-900 relative">
          {liveStream.status === 'LIVE' ? (
            <video 
              ref={videoRef}
              controls 
              className="w-full h-full"
              autoPlay
              playsInline
            >
              您的浏览器不支持视频播放。
            </video>
          ) : (
            <div className="flex items-center justify-center h-full">
              <div className="text-white text-center px-4">
                <p className="text-lg md:text-xl">直播未开始</p>
                <p className="text-sm md:text-base text-gray-400 mt-2">请等待主播开始直播</p>
              </div>
            </div>
          )}
          
          {/* 直播状态指示器 */}
          <div className="absolute top-4 left-4">
            <span className={`px-2 py-1 rounded text-xs font-medium ${
              liveStream.status === 'LIVE' 
                ? 'bg-red-500 text-white' 
                : 'bg-gray-500 text-white'
            }`}>
              {liveStream.status === 'LIVE' ? 'LIVE' : 'OFFLINE'}
            </span>
          </div>
          
          {/* 观看人数 */}
          <div className="absolute top-4 right-4 bg-black bg-opacity-75 text-white text-xs px-2 py-1 rounded">
            {liveStream.viewers || 0} 观看
          </div>
        </div>
        
        {/* 直播信息 */}
        <div className="p-4 md:p-6">
          <h1 className="text-xl md:text-2xl font-bold text-gray-900 mb-2">{liveStream.title}</h1>
          <p className="text-gray-600 mb-4 text-sm md:text-base">{liveStream.description}</p>
          
          <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between space-y-4 sm:space-y-0">
            <div className="flex items-center space-x-3 md:space-x-4">
              <Avatar 
                user={{
                  id: liveStream.userId || 0,
                  username: liveStream.username || '未知用户',
                  email: '',
                  avatar: undefined,
                  bio: '',
                  createdAt: liveStream.createdAt,
                  updatedAt: liveStream.createdAt
                }} 
                size="md" 
              />
              <div>
                <p className="font-medium text-gray-900 text-sm md:text-base">{liveStream.username || '未知用户'}</p>
                <p className="text-sm text-gray-500">
                  {liveStream.startedAt ? `开始于 ${new Date(liveStream.startedAt).toLocaleDateString()}` : '未开始'}
                </p>
              </div>
            </div>
            
            <div className="flex items-center space-x-3 md:space-x-4 w-full sm:w-auto">
              <div className="flex items-center space-x-2 text-gray-600 text-sm">
                <span>👁️</span>
                <span>{liveStream.viewers || 0} 次观看</span>
              </div>
              <button 
                onClick={handleLike}
                disabled={isLiked}
                className={`flex items-center space-x-2 px-4 py-2 rounded-full text-sm md:text-base ${
                  isLiked 
                    ? 'bg-red-100 text-red-600' 
                    : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                }`}
              >
                <span>👍</span>
                <span>{liveStream.likes || 0} 点赞</span>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default LiveStreamView; 